<script setup lang="ts">

import {Page} from "~/api/requestInstance";
import {ElForm, ElMessage, ElMessageBox} from "element-plus";
import {Search} from '@element-plus/icons-vue'
import {CommonSearchVO, Result, TableFieldVO} from "~/api/responseResult";
import {
  batchDeleteById,
  dataPageList,
  deleteAllByCriteriaRequest,
  deleteCommonSearchByPid,
  getCommonSearch,
  getIdentityByTable,
  getTableField,
  saveCommonSearch
} from "~/api/warehouse";
import {formatDateTime} from '~/utils';

const props = defineProps<{ table: string }>()
const router = useRouter()
const formRef = ref<InstanceType<typeof ElForm>>()
const operationLogRef = ref(null)
const permissionTableRef = ref(null)
const state: {
  page: Page,
  total: number,
  tableData: Array<any>,
  loading: boolean,
  formData: any,
  fieldList: Array<TableFieldVO>,
  commonSearch: Array<CommonSearchVO>,
  selectionIdArr: number[],
  // 1 管理员 2 普通用户 3 无身份
  identity: number
} = reactive({
  page: {
    pageNo: 1,
    pageSize: 10,
  },
  total: 0,
  tableData: [],
  loading: false,
  formData: {},
  fieldList: [],
  commonSearch: [],
  selectionIdArr: [],
  identity: 3,
})

const pageFun = {
  handleSizeChange: (pageSize: number) => {
    state.page.pageSize = pageSize
    query()
  },
  handleCurrentChange: (pageNo: number) => {
    state.page.pageNo = pageNo
    query()
  }
}

const query = async () => {
  console.log(state.formData)
  const json: any = {...state.page}
  json.tablePid = props.table
  json.queryCriteria = state.formData
  state.loading = true
  const res: Result<Array<any>> = await dataPageList(json)
  state.loading = false
  if (res.success) {
    state.tableData = res.data
    state.total = res.total
  }
}
const cleanUp = () => {
  const formData: any = {}
  state.fieldList.forEach(item => {
    if (item.fieldType === 'time' || item.fieldType === 'number') {
      formData[item.fieldApi] = [null, null]
    } else {
      formData[item.fieldApi] = null
    }
  });
  state.formData = formData
}


const initFieldList = async () => {
  const res: Result<Array<TableFieldVO>> = await getTableField({tablePid: props.table})
  if (res.success) {
    state.fieldList = res.data
    // 组装formData
    const formData: any = {}
    state.fieldList.forEach(item => {
      if (item.fieldType === 'time' || item.fieldType === 'number') {
        formData[item.fieldApi] = [null, null]
      } else {
        formData[item.fieldApi] = null
      }
    });
    state.formData = formData
  }
}
const initCommonSearch = async () => {
  const res: Result<Array<CommonSearchVO>> = await getCommonSearch({tablePid: props.table});
  if (res.success) {
    state.commonSearch = res.data
  }
}

const saveCommon = () => {
  ElMessageBox.prompt('请输入常用搜索名称', '保存常用搜索', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
      .then(async ({value}) => {
        const json: any = {}
        json.tablePid = props.table
        json.searchName = value
        json.searchContentMap = state.formData
        const res: Result<any> = await saveCommonSearch(json)
        if (res.success) {
          ElMessage({
            type: 'success',
            message: `保存成功`,
          })
          await initCommonSearch()
        }
      })
      .catch((e) => {
        console.log("失败")
      })
}

const replaceSearch = (searchContentMap: any) => {
  state.formData = searchContentMap
  query()
}

const indexMethod = (index: number) => {
  return (state.page.pageNo - 1) * state.page.pageSize + index + 1
}
const handleSelectionChange = (val: any[]) => {
  const selectionIdArr = val.map(item => {
    return item.id;
  })
  state.selectionIdArr = selectionIdArr
}
const batchDelete = async () => {
  if (state.selectionIdArr.length > 0) {
    ElMessageBox.confirm(
        '此次删除' + state.selectionIdArr.length + '条，确认删除吗?',
        '删除提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
        }
    )
        .then(async () => {
          const res: Result<any> = await batchDeleteById({ids: state.selectionIdArr, tablePid: props.table})
          if (res.success) {
            ElMessage.success({
              message: "删除成功"
            })
            state.page.pageNo = 1
            await query();
          }
        })
        .catch(() => {
          console.log("异常")
        })
  } else {
    ElMessage.warning({
      message: "请选择数据"
    })
  }
}
const openOperationLog = () => {
  if (operationLogRef.value == null) {
    return
  }
  operationLogRef.value.open({tablePid: props.table})
}

const getIdentity = async () => {
  const res: Result<number> = await getIdentityByTable({tablePid: props.table})
  if (res.success) {
    state.identity = res.data
  }
}

/**
 * 设置权限
 */
const setAuthority = () => {
  if (!permissionTableRef.value) {
    return
  }
  permissionTableRef.value.open({tablePid: props.table})
}

const deleteCommonSearch = (pid: string) => {
  ElMessageBox.confirm(
      '确认删除吗?',
      '删除提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }
  )
      .then(async () => {
        const res: Result<any> = await deleteCommonSearchByPid({pid: pid})
        if (res.success) {
          ElMessage.success({
            message: '删除成功',
          })
          await initCommonSearch()
        }
      })
      .catch(() => {
        console.log("异常")
      })
}

const deleteAllByCriteria = async () => {
  await query()
  ElMessageBox.confirm(
      '此次删除' + state.total + '条,确认删除吗?',
      '删除提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }
  )
      .then(async () => {
        const json: any = {...state.page}
        json.tablePid = props.table
        json.queryCriteria = state.formData
        state.loading = true
        const res: Result<any> = await deleteAllByCriteriaRequest(json)
        state.loading = false
        if (res.success) {
          ElMessage.success({
            message: '删除成功',
          })
          await query()
        }
      })
      .catch(() => {
        console.log("异常")
      })


}
onBeforeMount(() => {
  initFieldList()
  initCommonSearch()
  getIdentity()
  query()
})

defineExpose({
  props,
  pageFun,
  router,
  formRef,
  Search,
  query,
  cleanUp,
  saveCommon,
  formatDateTime,
  replaceSearch,
  indexMethod,
  handleSelectionChange,
  batchDelete,
  operationLogRef,
  openOperationLog,
  setAuthority,
  permissionTableRef,
  deleteCommonSearch,
  deleteAllByCriteria
})

</script>

<template>
  <el-row :gutter="1">
    <el-col :span="4">
      <el-card style="height: calc(100vh - 102px);overflow: auto" class="box-card">
        <div>
          <el-collapse model-value="自定义搜索">
            <el-collapse-item name="常用搜索">
              <template #title>
                <h1 style="font-size: 20px;">常用搜索</h1>
              </template>


              <div style="margin-left: 10px">
                <el-menu class="el-menu-vertical-demo">
                  <el-menu-item v-for="item in state.commonSearch" :index="item.pid" :key="item.pid"
                                @click="replaceSearch(item.searchContentMap)">
                    <div style="width: 100%">
                      <span style="float: left">{{ item.searchName }}</span>
                      <span style="float: right" @click.stop="deleteCommonSearch(item.pid)">删除</span>
                    </div>

                  </el-menu-item>
                </el-menu>
              </div>


            </el-collapse-item>

            <el-collapse-item name="自定义搜索">
              <template #title>
                <h1 style="font-size: 20px;">自定义搜索</h1>
              </template>
              <div style="margin-left: 10px">
                <div>
                  <el-row>
                    <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="8">
                      <el-button style="width: 80px;margin: 5px" size="small" :icon="Search" type="primary" @click="query">查询</el-button>
                    </el-col>

                    <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="8">
                      <el-button style="width: 80px;margin: 5px" size="small" type="danger" @click="cleanUp">清空</el-button>
                    </el-col>

                    <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="8">
                      <el-button style="width: 80px;margin: 5px" size="small" type="primary" @click="saveCommon">保存常用</el-button>
                    </el-col>

                  </el-row>
                </div>

                <div style="margin-top: 20px">
                  <el-form
                      ref="formRef"
                      :model="state.formData"
                      label-width="auto"
                      label-position="top"
                      size="small"
                  >
                    <div v-for="item in state.fieldList">
                      <el-form-item v-if="item.fieldType === 'text'" :label="item.fieldName">
                        <el-input style="width: 100%" v-model="state.formData[item.fieldApi]"/>
                      </el-form-item>
                      <el-form-item v-if="item.fieldType === 'time'" :label="item.fieldName">
                        <el-date-picker
                            type="datetimerange"
                            style="width: 100%"
                            v-model="state.formData[item.fieldApi]"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                        >
                        </el-date-picker>
                      </el-form-item>
                      <el-form-item v-if="item.fieldType === 'number'" :label="item.fieldName">
                        <el-row>
                          <el-col :span="11">
                            <el-input @input="(value) => {
                              if (isNaN(value)) {
                                state.formData[item.fieldApi][0] = null
                              }}"
                                      style="width: 100%;" v-model="state.formData[item.fieldApi][0]"/>
                          </el-col>
                          <el-col style="text-align: center;" :span="2">
                            ~
                          </el-col>
                          <el-col :span="11">
                            <el-input @input="(value) => {
                              if (isNaN(value)) {
                                state.formData[item.fieldApi][1] = null
                              }}"
                                      style="width: 100%;" v-model="state.formData[item.fieldApi][1]"/>
                          </el-col>
                        </el-row>

                      </el-form-item>
                    </div>
                  </el-form>
                </div>
              </div>
            </el-collapse-item>

          </el-collapse>
        </div>
      </el-card>
    </el-col>
    <el-col :span="20">
      <el-card style="height: calc(100vh - 102px);overflow: auto;" class="box-card">
        <div>
          <el-row>
            <el-col :span="24">
              <div style="float: right">
                <el-button size="small" type="primary" @click="router.push('/import/' + table)">导入</el-button>
                <el-button size="small" type="primary" @click="batchDelete">删除</el-button>
                <el-button size="small" type="primary" @click="deleteAllByCriteria">删除所有</el-button>
                <el-button size="small" type="primary" @click="openOperationLog">操作记录</el-button>
                <el-button size="small" v-if="state.identity === 1" type="primary" @click="setAuthority">设置权限
                </el-button>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-table
            @selection-change="handleSelectionChange"
            :data="state.tableData"
            style="width: 100%;margin-top: 10px"
            v-loading="state.loading">
          <el-table-column type="selection" width="40"/>
          <el-table-column type="index" :index="indexMethod" width="100" label="序号"/>
          <el-table-column
              min-width="200"
              v-for="item in state.fieldList"
              :prop="item.fieldApi" :label="item.fieldName">
            <template #default="scope">
              <el-popover
                  v-if="scope.row[item.fieldApi] && scope.row[item.fieldApi].length > 12"
                  placement="bottom"
                  :width="200"
                  trigger="click"
                  :content="item.fieldType !== 'time' ? scope.row[item.fieldApi] : formatDateTime(scope.row[item.fieldApi], 'YYYY-MM-DD hh:mm:ss')"
              >
                <template #reference>
                  <div class="cell-text">
                    {{
                      item.fieldType !== 'time' ? scope.row[item.fieldApi] : formatDateTime(scope.row[item.fieldApi], 'YYYY-MM-DD hh:mm:ss')
                    }}
                  </div>
                </template>
              </el-popover>
              <div v-else class="cell-text">
                {{
                  item.fieldType !== 'time' ? scope.row[item.fieldApi] : formatDateTime(scope.row[item.fieldApi], 'YYYY-MM-DD hh:mm:ss')
                }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            style="margin-top: 10px;text-align: right"
            v-model:currentPage="state.page.pageNo"
            :page-sizes="[10, 20, 50, 100, 500]"
            :page-size="state.page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="state.total"
            @size-change="pageFun.handleSizeChange"
            @current-change="pageFun.handleCurrentChange"
        >
        </el-pagination>
      </el-card>
    </el-col>
    <OperationLog ref="operationLogRef"/>
    <SetPermissionTable ref="permissionTableRef"/>
  </el-row>

</template>
<style lang="scss" scoped>

::v-deep .el-collapse-item__content {
  padding-bottom: 5px
}

::v-deep .el-form--label-top .el-form-item__label {
  padding: 0 0 0 0;
}

::v-deep .el-form-item--small.el-form-item {
  margin-bottom: 0px;
}

::v-deep .el-menu-item {
  height: 40px;
  line-height: 40px;
}

.cell-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
<route lang="yaml">
meta:
  layout: home
</route>
